package cn.wolfcode.cloud.shop.resolve;

import cn.wolfcode.cloud.shop.anno.UserParam;
import cn.wolfcode.cloud.shop.domain.User;
import cn.wolfcode.cloud.shop.redis.MemberRedisKey;
import cn.wolfcode.cloud.shop.util.CookieUtil;
import cn.wolfcode.cloud.shop.util.JSONUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @author Administrator
 */
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

//    @Autowired
//    private IUserService userService;


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterAnnotation(UserParam.class) != null && parameter.getParameterType().equals(User.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest req = webRequest.getNativeRequest(HttpServletRequest.class);
        if(req != null){
            Cookie cookie = CookieUtil.getCookie(req, CookieUtil.TOKEN_IN_COOKIE_NAME);
            if(cookie!=null){
                String json = redisTemplate.opsForValue().get(MemberRedisKey.USER_TOKEN.getRealKey(cookie.getValue()));
                if(StringUtils.isNotEmpty(json)){
                    return JSONUtil.parseObject(json,User.class);
                }
            }
        }
        return null;
    }
}
